package com.zengjin.test.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.util.Collections;
import java.util.List;

/**
 * @author 19324
 */
@Data
public class PageResponse<T> {

    //1.总条数
    private Long total;

    //2.总页数
    private Long pages;

    //3.集合
    private List<T> data;

    //
    public static <PO, VO> PageResponse<VO> of(Page<PO> page, Class<VO> voClass) {
        PageResponse<VO> pageResponse = new PageResponse<>();
        //1.总条数
        pageResponse.setTotal(page.getTotal());
        //2.总页数
        pageResponse.setPages(page.getPages());
        //3.集合
        List<PO> records = page.getRecords();
        if (CollUtil.isEmpty(records)) {
            pageResponse.setData(Collections.emptyList());
            return pageResponse;
        }
        //4.转VO
        pageResponse.setData(BeanUtil.copyToList(records, voClass));
        return pageResponse;

    }

    /**
     * 封装分页数据，连表查询
     */
    public static <PO, VO> PageResponse<VO> of(Page<PO> page, List<VO> listVO) {
        PageResponse<VO> pageResponse = new PageResponse<>();

        long len = listVO.size();

        // 1. 设置总条数
        pageResponse.setTotal(len);

        Long pages = (len % page.getSize() == 0 ? len / page.getSize() : len / page.getSize() + 1);

        // 2. 设置总页数
        pageResponse.setPages(pages);

        //3.根据分页信息截取集合
        long current = page.getCurrent();
        long size = page.getSize();
        long start = (current - 1) * size;
        long end = Math.min(start + size, len);

        if (start >= end) {
            pageResponse.setData(Collections.emptyList());
            return pageResponse;
        } else {
            listVO = listVO.subList((int) start, (int) end);
        }
        // 4. 设置数据列表
        pageResponse.setData(listVO);

        return pageResponse;
    }


}
